# coding:utf-8

dict1 = {"a": 1, "b": 2, "c": 3, 4: "d"}
print(dict1["a"], dict1[4])
# print(dict1["d"])
dict1["a"] = 2
print(dict1)

del dict1[4]
print(dict1)

dict1.clear()
print(dict1)

# 不允许同一个键出现两次，创建时如果同一个键被赋值两次，会覆盖第一个值
dict2 = {"a": 1, "b": 2, "a": 3}
print(dict2)

# 键必须不可变，所以可以用数字，字符串或元组充当，但不可以用列表
# list objects are unhashable
# dict3 = {["a"]: 1, "b": 2}
# print(dict3)

print(len(dict2))
print(str(dict2))
print(type(dict2))

dict3 = dict2.copy()
print(dict2, dict3)

tup = ("a", "b", "c")
dict4 = dict.fromkeys(tup)
print(dict4)
dict5 = dict.fromkeys(tup, 1)
print(dict5)

print(dict5.get("d"))
print(dict5.__contains__("d"))  # Python 3.X 里不包含 has_key() 函数，被 __contains__(key) 替代
print(dict5.items())
for key, val in dict5.items():
    print(key, val)
print(dict5.keys())
print(dict5.setdefault("a", 2))  # 与get类似，但如果键不存在将会添加并设置为默认
print(dict5.setdefault("e", 3))
print(dict5)
dict6 = {"c": 3}
dict6.update(dict5)  # 将dict6中的键值对合并到dict6中
print(dict6)

print(dict6.values())

dict6.pop("b")  # 删除字典给定键key对应的值，并返回值，key必须给出，否则返回default
print(dict6)
print(dict6.pop("f", 5))

print(dict6.popitem())  # 随机返回并删除字典中的一对键和值
print(dict6)
